<template>
  <el-card style="height: 100%;">
    <div class="card-title">健康建议管理</div>
    <div class="search-control">
      <div class="left">
        <el-button type="primary" icon="Plus" @click="openInsertDialog">新增</el-button>
      </div>
    </div>

    <el-table :data="healthSuggestionsList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column prop="stars" label="星级" align="center">
        <template #default="scope">
          <span v-for="star in scope.row.stars" :key="star">⭐</span>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="内容" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button type="primary" icon="Edit" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-popconfirm title="是否删除该条数据?" @confirm="deleteRow(scope.row.id)">
            <template #reference>
              <el-button type="danger" icon="DeleteFilled" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination-container"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalData">
    </el-pagination>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑健康建议' : '新增健康建议'" width="30%">
      <el-form :model="healthSuggestionsForm" ref="formRef" label-width="80px" style="padding: 0px 20px">
        <el-form-item label="星级" prop="stars" v-if="!isEdit">
          <el-select v-model="selectedStar" placeholder="请选择星级" @change="handleStarChange">
            <el-option
              v-for="rule in healthRulesList"
              :key="rule.id"
              :label="rule.stars"
              :value="rule.stars"
            >
              {{ rule.stars }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="healthSuggestionsForm.content"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveHealthSuggestions">{{ isEdit ? '编辑' : '新增' }}</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import {IHealthSuggestions} from "@/views/main/health/suggestions/types";
import {IHealthRules} from "@/views/main/health/rule/types";
import {
  addHealthSuggestion, deleteHealthSuggestion,
  queryAllSuggestions,
  queryRulesList,
  updateHealthSuggestion
} from "@/service/common/health";

export default defineComponent({
  setup() {
    const healthSuggestionsList = ref<IHealthSuggestions[]>([]);
    const healthSuggestionsForm = ref<IHealthSuggestions>({
      id: 0,
      healthRuleId: 0,
      stars: 0,
      content: ''
    });
    const healthRulesList = ref<IHealthRules[]>([]);
    const selectedStar = ref<string>('');
    const currentPage = ref<number>(1);
    const pageSize = ref<number>(10);
    const totalData = ref<number>(0);
    const dialogVisible = ref<boolean>(false);
    const isEdit = ref<boolean>(false);
    const selectedRows = ref<IHealthSuggestions[]>([]);

    const fetchHealthSuggestions = () => {
      queryAllSuggestions(currentPage.value, pageSize.value)
        .then(response => {
          healthSuggestionsList.value = response.records;
          totalData.value = response.total;
        })
        .catch(error => {
          console.error("Error fetching health suggestions:", error);
        });
    };

    const fetchHealthRules = () => {
      queryRulesList(currentPage.value, pageSize.value)
        .then(response => {
          healthRulesList.value = response.records;
        })
        .catch(error => {
          console.error("Error fetching health rules:", error);
        });
    };

    const handleStarChange = (value: number) => {
      const selectedRule = healthRulesList.value.find(rule => rule.stars === value);
      if (selectedRule) {
        healthSuggestionsForm.value.healthRuleId = selectedRule.id;
      }
    };

    const handleSizeChange = (size: number) => {
      pageSize.value = size;
      fetchHealthSuggestions();
    };

    const handleCurrentChange = (page: number) => {
      currentPage.value = page;
      fetchHealthSuggestions();
    };

    const handleSelectionChange = (val: IHealthSuggestions[]) => {
      selectedRows.value = val;
    };

    const openInsertDialog = () => {
      isEdit.value = false;
      dialogVisible.value = true;
      healthSuggestionsForm.value = {
        id: 0,
        healthRuleId: 0,
        stars: 0,
        content: ''
      };
      fetchHealthRules();
    };

    const openEditDialog = (row: IHealthSuggestions) => {
      isEdit.value = true;
      dialogVisible.value = true;
      healthSuggestionsForm.value = { ...row };
    };

    const saveHealthSuggestions = () => {
      if (!isEdit.value && !selectedStar.value) {
        ElMessage.error("请选择星级");
        return;
      }
      if (isEdit.value) {
        updateHealthSuggestion(healthSuggestionsForm.value)
          .then(() => {
            dialogVisible.value = false;
            ElMessage.success("健康建议更新成功");
            fetchHealthSuggestions();
          })
          .catch(error => {
            console.error("Error updating health suggestions:", error);
          });
      } else {
        addHealthSuggestion(healthSuggestionsForm.value)
          .then(() => {
            dialogVisible.value = false;
            ElMessage.success("健康建议新增成功");
            fetchHealthSuggestions();
          })
          .catch(error => {
            console.error("Error adding health suggestions:", error);
          });
      }
      selectedStar.value = '';
    };

    const deleteRow = (id: number) => {
      deleteHealthSuggestion(id)
        .then(() => {
          ElMessage.success("健康建议删除成功");
          fetchHealthSuggestions();
        })
        .catch(error => {
          console.error("Error deleting health suggestions:", error);
        });
    };

    onMounted(() => {
      fetchHealthSuggestions();
    });

    return {
      healthSuggestionsList,
      healthSuggestionsForm,
      healthRulesList,
      selectedStar,
      currentPage,
      pageSize,
      totalData,
      dialogVisible,
      isEdit,
      selectedRows,
      fetchHealthSuggestions,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      openInsertDialog,
      openEditDialog,
      saveHealthSuggestions,
      deleteRow,
      handleStarChange
    };
  }
});
</script>

<style scoped>
.card-title {
  font-size: 20px;
  margin-bottom: 20px;
}
.search-control {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.dialog-footer {
  text-align: right;
  padding: 10px 0;
}
</style>
